<template>
    <div class="content_panel project_modules">
        <div class="content_panel_top">
            <h3 class="panel_title">
                <span>{{$t('common.remitReview')}}</span>
            </h3>
            <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item prop="orderId" label="">
                            <el-input v-model="form.orderId" :placeholder="$t('common.innerOrderId')" clearable></el-input><!--内部订单号-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="appName" label="">
                            <select-app-list v-model="form.appName" :placeholder="$t('system.appName')"></select-app-list><!--app名称-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="userPhone" label="">
                            <el-input v-model="form.userPhone" :placeholder="$t('common.mobileNumber')" clearable></el-input><!--手机号码-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="derateId" label="">
                            <el-input v-model="form.derateId" :placeholder="$t('common.remitApplyId')" clearable></el-input><!--减免申请编号-->
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item prop="userId" label="">
                            <el-input v-model="form.userId" clearable placeholder="UserId" maxlength="10"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="derateApplyTime" label=""><!--申请时间-->
                            <el-date-picker
                                    style="width:100%"
                                    v-model="form.derateApplyTime"
                                    type="datetimerange"
                                    format="yyyy-MM-dd HH:mm:ss"
                                    value-format="timestamp"
                                    range-separator="-"
                                    :default-time="['00:00:00', '23:59:59']"
                                    :start-placeholder="$t('common.applyStartTime')"
                                    :end-placeholder="$t('common.applyEndTime')"
                                    clearable>
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item prop="derateType" label="">
                            <el-select v-model="form.derateType" clearable :placeholder="$t('verify.plsChoose')" style="width: 100%;">
                                <el-option v-for="(item, $index) in deductionTypeList" :key="$index" :value="item.value" :label="item.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <!-- 伪名 -->
                    <el-col :span="6">
                        <el-form-item prop="whiteProductName" v-if="domain == 'Bene'"> <!---->
                            <el-input v-model="form.whiteProductName" :placeholder="$t('common.productName')" clearable><!----></el-input>
                        </el-form-item>
                        <el-form-item prop="kana" v-else> <!--姓名-->
                            <select-kana-list v-model="form.kana" :multiple="false" :placeholder="$t('finance.pseudonym')"></select-kana-list><!--app名称-->
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item>
                            <el-button @click="search" icon="el-icon-search" type="primary">{{ $t('common.search') }}</el-button>
                            <el-button @click="exportExcel" icon="el-icon-upload2" type="primary">{{ $t('common.export') }}</el-button>
                            <el-button type="primary" @click="aduitBatchDialog()" :disabled="selectedIdList.derateIds.length <= 0">{{ $t('common.batchReview') }}</el-button>
                            <el-button v-if="exportButtonShow" @click="reliefConfiguration" type="primary">{{ $t('common.reliefConfiguration') }}</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div><!--content_panel_top-->
        <div class="module_content">
            <div class="content_panel project_modules">
                <div class="table_list">
                    <el-table ref="table" :data="tableData" style="width: 100%;" :highlight-current-row="true"
                              :max-height="tableMaxHeight" @selection-change="handleTableSelect"
                              :row-key="handleRowKey">
                        <el-table-column :label="$t('common.allChoose')" type="selection" width="50"></el-table-column>
                        <el-table-column :label="$t('common.remitApplyId')" prop="derateId" width="200"></el-table-column><!--减免申请编号-->
                        <el-table-column :label="$t('common.innerOrderId')" prop="orderId" width="200"></el-table-column><!--内部订单号-->
                        <el-table-column :label="$t('system.appName')" prop="appName" min-width="130"></el-table-column><!--APP名称-->
                        <el-table-column v-if="domain=='Bene'" :label="$t('finance.productName')" prop="whiteProductName" min-width="130"></el-table-column><!--伪名-->
                        <el-table-column v-else :label="$t('finance.pseudonym')" prop="kana" min-width="130"></el-table-column><!--伪名-->

                        <el-table-column label="UserId" prop="userId" width="150"></el-table-column>
                        <el-table-column :label="$t('common.name')"  prop="userName" min-width="100"></el-table-column><!--姓名-->
                        <el-table-column :label="$t('common.mobileNumber')" prop="userPhone" width="150"></el-table-column><!--手机号码-->
                        <el-table-column :label="$t('common.applyDate')" prop="derateApplyTime" width="170">
                            <template slot-scope="{ row }">{{ row.derateApplyTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template><!--申请时间-->
                        </el-table-column>

                        <el-table-column prop="totalPeriods" v-if="showSpread" :label="$t('install.totalBorrowPeriod')" min-width="150"></el-table-column><!--借款总周期-->
                        <el-table-column prop="currentPeriod" v-if="showSpread" :label="$t('install.currentBorrowPeriod')" min-width="150"></el-table-column><!--借款当前周期-->

                        <el-table-column :label="$t('common.remitAmount')" prop="derateAmount" width="200"></el-table-column><!--减免金额-->
                        <el-table-column :label="$t('common.overduePeriod')" prop="teamName" width="100"></el-table-column><!--逾期阶段-->
                        <el-table-column :label="$t('common.remitType')" prop="derateType" width="150">
                            <template slot-scope="{ row }">{{ row.derateType | deductionType }}</template><!--减免类型-->
                        </el-table-column>
                        <el-table-column :label="$t('common.applyPerson')" prop="collectionUserName" width="150"></el-table-column><!--申请人-->
                        <el-table-column :label="$t('common.validityPeriod')" prop="validiteTime" width="170">
                            <template slot-scope="{ row }">{{ row.validiteTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template><!--有效期-->
                        </el-table-column>
                        <el-table-column :label="$t('common.colReviewTime')" prop="collectionAuditTime" width="170">
                            <template slot-scope="{ row }">
                                {{ row.collectionAuditTime | formatDate('yyyy-MM-dd hh:mm:ss') }}
                            </template><!--催收审核时间-->
                        </el-table-column>
                        <el-table-column :label="$t('common.operation')" width="120" fixed="right">
                            <template slot-scope="{ row }">
                                <el-button type="text" @click="aduitSingleDialog(row)">{{ $t('common.review') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--分页组件-->
                    <pagination @pageChange="pageChange" :page="page"></pagination>
                </div><!--module_content-->
            </div>
        </div><!--module_content-->

        <!-- 单行审核 -->
        <el-dialog :title="$t('common.remitReview')" :visible.sync="singleAduitVisible">
            <el-form :model="formSingleAduit">
                <el-form-item :label="$t('common.borrowerName') + '：'" :label-width="formLabelWidth" prop="userName"><!--借款人姓名-->
                    <span>{{formSingleAduit.userName}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.innerOrderId') + '：'" :label-width="formLabelWidth" prop="orderId"><!--内部订单号-->
                    <span>{{formSingleAduit.orderId}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.contractAmount') + '：'" :label-width="formLabelWidth" prop="contractAmount"><!--合同金额-->
                    <span>{{formSingleAduit.contractAmount}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.restRepay') + '：'" :label-width="formLabelWidth" prop="restRepay"><!--挂账金额-->
                    <span>{{formSingleAduit.restRepay}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.shouldRepayAmount') + '：'" :label-width="formLabelWidth" prop="lateRepay"><!--应还金额-->
                    <span>{{formSingleAduit.lateRepay}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.canRemitAmount') + '：'" :label-width="formLabelWidth" prop="canDerateAmount"><!--可减免金额-->
                    <span>{{formSingleAduit.canDerateAmount}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.applyRemitAmount') + '：'" :label-width="formLabelWidth" prop="derateAmount"><!--申请减免金额-->
                    <span>{{formSingleAduit.derateAmount}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.validityPeriod') + '：'" :label-width="formLabelWidth" prop="validiteTime"><!--有效期-->
                    <span>{{formSingleAduit.validiteTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</span>
                </el-form-item>
                <el-form-item :label="$t('common.remitType') + '：'"  :label-width="formLabelWidth" prop="derateType"><!--减免类型-->
                    <span>{{ formSingleAduit.derateType | deductionType }}</span>
                </el-form-item>
                <el-form-item :label="$t('common.applyReason') + '：'" :label-width="formLabelWidth" prop="reason"><!--申请理由-->
                    <span>{{formSingleAduit.reason}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.colReviewPerson') + '：'" :label-width="formLabelWidth" prop="collectionAuditor"><!--催收审核人-->
                    <span>{{formSingleAduit.collectionAuditor}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.colRemark') + '：'" :label-width="formLabelWidth" prop="collectionRemark"><!--催收备注-->
                    <span>{{formSingleAduit.collectionRemark}}</span>
                </el-form-item>
                <el-form-item :label="$t('common.finRemark') + '：'" :label-width="formLabelWidth" prop="financialRemark"><!--财务备注-->
                    <el-input type="textarea" v-model="batchAduitForm.financialRemark" :placeholder="$t('verify.plsInput')" maxlength="200"></el-input>
                </el-form-item>
                <el-form-item label="" :label-width="formLabelWidth">
                    <el-radio-group v-model="batchAduitForm.derateResult">
                        <el-radio label="1">{{ $t('common.refuse') }}</el-radio>
                        <el-radio label="2">{{ $t('common.pass') }}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="batchAduitComfirm('single')">{{ $t('common.confirm') }}</el-button>
                <el-button @click="singleAduitVisible = false">{{ $t('common.cancel') }}</el-button>
            </div>
        </el-dialog>
        <!-- 批量审核 -->
        <!-- batchAduitForm:{
                  derateIds:'',     //金额减免申请编号拼接，例如“aaa,bbb,cc”
                  financialAuditor:'',  //审核人
                  financialAuditorId:'',    //	审核人id
                  financialRemark:'',   //审核意见
                  derateResult:''   //审核结果
              }   -->
        <el-dialog :title="$t('common.batchReview')" :visible.sync="batchAduitVisible">
            <el-form :model="batchAduitForm">
                <el-form-item label="" prop="username">
                    <span>{{ $t('common.batchReviewXApply',{x: selectedIdList.derateIds.length}) }}</span>
                    <el-input type="textarea" v-model="batchAduitForm.financialRemark" :placeholder="$t('verify.plsInput')" maxlength="200"></el-input>
                </el-form-item>
                <el-form-item label="">
                    <el-radio-group v-model="batchAduitForm.derateResult">
                        <el-radio label="1">{{ $t('common.refuse') }}</el-radio>
                        <el-radio label="2">{{ $t('common.pass') }}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" :disabled="selectedIdList.derateIds.length===0" @click="batchAduitComfirm('batch')">{{ $t('common.confirm') }}</el-button>
                <el-button @click="batchAduitVisible = false">{{ $t('common.cancel') }}</el-button>
            </div>
        </el-dialog>
        <!-- 批量审核         -->

        <!--减免配置弹框-->
        <el-dialog :visible.sync="configurationDialog.showConfigurationDialog" width="416px" :title="$t('common.reliefConfiguration')">
            <el-form :model="configurationDialog.form" ref="configurationForm" :rules="configurationDialog.rules">
                <el-form-item prop="derateAmount" :label="$t('common.maxAmountByAutoCheckPass') + ' : '">
                    <el-input v-model="configurationDialog.form.derateAmount" :placeholder="$t('verify.plsInput')" clearable style="marginTop: 10px"></el-input><!--自动审核通过的最大金额-->
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="configurationDialog.showConfigurationDialog = false" type="default">{{$t('common.cancel')}}</el-button>
                <el-button @click="reliefConfigurationComfirm" type="primary">{{$t('common.confirmOk')}}</el-button>
            </div>
        </el-dialog>
    </div>

</template>

<script>
    import Pagination from "@/components/pagination";
    import mixin from "@/service/mixin";
    import SelectAppList from '@/components/select-app-list';
    import {domain} from '@/config/'
    import SelectKanaList from '@/components/select-kana-list';

    let that = null;
    export default {
        name: "reduceAuditReduce",
        components: {
            Pagination,
            SelectAppList,
            SelectKanaList
        },
        mixins: [mixin],
        data() {
            return {
                domain:'',
                showSpread:false,
                form: {
                    orderId: "",
                    derateApplyTime: "",
                    userPhone: "",
                    withdrawAccount: "",
                    derateId: "",
                    userId: "",
                    product: "",
                    derateType: "",
                    appName: '',
                    kana:'',
                    whiteProductName:'',
                },
                rules: {
                    orderId: [],
                    derateApplyTime: [],
                    userPhone: [],
                    withdrawAccount: [],
                    derateId: [],
                    userId: [],
                    product: [],
                    derateType: []
                },
                deductionTypeList: [
                    { value: '', label: this.$t('common.all') },// 全部
                    { value: '0', label: this.$t('common.validityRemit') },// 有效期减免
                    { value: '1', label: this.$t('common.foreverRemit') },// 永久性减免
                ],
                singleAduitVisible: false, //单行审核弹窗
                batchAduitVisible: false, //批量审核弹窗
                formSingleAduit: {
                    userName: "",
                    orderId: ""
                }, //单行审核展示数据
                formLabelWidth: this.$i18n.locale === 'zhCN' ? '125px' : "250px",
                selectedIdList: {
                    //复选的金额减免申请编号
                    derateIds: []
                },
                batchAduitForm: {
                    derateId: "",    //单笔金额减免申请编号
                    derateIds: "", //金额减免申请编号拼接，例如“aaa,bbb,cc”
                    financialAuditor: "", //审核人
                    financialAuditorId: "", //	审核人id
                    financialRemark: "", //审核意见
                    derateResult: "" //审核结果
                },
                configurationDialog: {
                    showConfigurationDialog: false,
                    form: {
                        derateAmount: ''
                    },
                    rules: {
                        derateAmount: [
                            {required: true, message: this.$t('verify.plsInput'), trigger: 'blur'},
                            {pattern: /^(0|[1-9]\d{0,7})$/, message: this.$t('verify.amountRange')},
                        ]
                    },
                }
            };
        },
        computed: {
            exportButtonShow() {
                // 减免配置按钮展示权限
                return this.$store.getters.checkUserAuthority('finance.remit.review.remissionControl');
            },
        },
        methods: {
            getTableData(page = this.page) {
                let params = this.fillParams(page);
                this.$api.finance.remit.queryUnAuditDerateInfo(params).then(res => {
                    let {status, data, error} = res;
                    if ("1" === status && "00000000" === error && data) {
                        this.tableData = data.resultData;
                        this.setPage(data.page, this.page);
                    }
                });
            },
            search() {
                this.page.currentPage = 1;
                this.getTableData();
            },
            exportExcel() {
                let params = this.fillParams();
                const user = this.$storage.get("user");
                const language = this.$storage.getLocal('language');
                params.language = language;
                params.token = user.token;
                const {$apiConf} = this;
                const url = this.$urlUtil.fillParams(params, $apiConf.baseUrl + $apiConf.urlType.finance.remit.unAuditDerateExcel, ["page"]);
                this.$openNewBlank(url);
            },
            fillParams(page = this.page) {
                const form = this.form;
                const params = {
                    orderId: "",
                    derateApplyTimeStart: "",
                    derateApplyTimeEnd: "",
                    userPhone: "",
                    withdrawAccount: "",
                    derateId: "",
                    userId: "",
                    product: "",
                    derateType: "",
                    appName: '',
                    kana:'',
                    whiteProductName:'',
                    page: {
                        pageNo: page.currentPage,
                        pageSize: this.page.pageSize
                    }
                };
                Object.keys(form).forEach(key => {
                    if (typeof form[key] === "string" && form[key]) {
                        form[key] = form[key].trim();
                        params[key] = form[key];
                    }
                });

                if (form.derateApplyTime) {
                    params.derateApplyTimeStart = form.derateApplyTime[0];
                    params.derateApplyTimeEnd = form.derateApplyTime[1];
                }
                return params;
            },
            // 列表多选处理
            handleTableSelect(val) {
                this.selectedIdList.derateIds = [];
                val.forEach(item => {
                    this.selectedIdList.derateIds.push(item.derateId);
                });
            },
            // 处理行数据
            handleRowKey(row) {
                return row.id;
            },
            aduitSingleDialog(row) {
                Object.assign(this.formSingleAduit, row);
                this.singleAduitVisible = true;
                const user = this.$storage.get("user");
                this.batchAduitForm.derateIds = '';
                this.batchAduitForm.derateId = row.derateId;
                this.batchAduitForm.financialAuditor = user.username;
                this.batchAduitForm.financialAuditorId = user.id;
                this.batchAduitForm.financialRemark = "";
                this.batchAduitForm.derateResult = "";
            },
            //批量审核弹窗
            aduitBatchDialog() {
                // /* eslint-disable */
                // Objeact.assign(this.batchAduitForm,{
                //   derateIds:'',     //金额减免申请编号拼接，例如“aaa,bbb,cc”
                //   financialAuditor:'',  //审核人
                //   financialAuditorId:'',    //	审核人id
                //   financialRemark:'',   //审核意见
                //   derateResult:''   //审核结果
                // });
                const user = this.$storage.get("user");
                // params.token = user.token;
                this.batchAduitForm.derateId = '';
                this.batchAduitForm.derateIds = this.selectedIdList.derateIds.join(",");
                this.batchAduitForm.financialAuditor = user.username;
                this.batchAduitForm.financialAuditorId = user.id;
                this.batchAduitForm.financialRemark = "";
                this.batchAduitForm.derateResult = "";
                this.batchAduitVisible = true;
            },
            //批量审核确定
            batchAduitComfirm(type) {
                let _this = this;
                if (this.batchAduitForm.financialRemark.trim() == "") {
                    this.$message.error(this.$t('verify.plsInputRemark'));
                    return;
                } else if (this.batchAduitForm.derateResult.trim() == "") {
                    this.$message.error(this.$t('verify.plsChooseReviewType'));//请选择审核方式
                    return;
                } else {
                    switch (type) {
                        case "single":
                            this.$api.finance.remit.auditProcess(this.batchAduitForm).then(res => {
                                const {status, error} = res;
                                if ("1" === status && "00000000" === error) {
                                    _this.singleAduitVisible = false;
                                    _this.$message.success(_this.$t('common.successfulOperation'));
                                    this.getTableData();
                                }
                            });
                            break;
                        case "batch":
                            this.$api.finance.remit.auditBatchProcess(this.batchAduitForm).then(res => {
                                const {status, error, data} = res;
                                if ("1" === status && "00000000" === error) {
                                    _this.batchAduitVisible = false;
                                    _this.$message.success(
                                        this.$t('common.successfulOperation') +
                                        data.successCount +
                                        this.$t('common.failedOperation') +
                                        data.faildCount +
                                        "。"
                                    );
                                    this.getTableData();
                                }
                            });
                            break;
                        default:
                            break;
                    }

                }
            },
            //减免配置弹框
            reliefConfiguration() {
                this.$api.finance.remit.queryDerateCfgInfo().then(res => {
                    let {status, data, error} = res;
                    if ("1" === status && "00000000" === error && data) {
                        this.configurationDialog.form = Object.assign({}, data);
                        this.configurationDialog.showConfigurationDialog = true;
                        this.$nextTick(() => {
                            this.$refs.configurationForm.clearValidate();
                        });
                    }
                });
            },
            //减免配置确认
            reliefConfigurationComfirm() {
                this.$refs.configurationForm.validate((val) => {
                    if (val) {
                        const params = {
                            derateAmount: this.configurationDialog.form.derateAmount
                        };
                        this.$api.finance.remit.editDerateCfg(params).then(res => {
                            let {status, error} = res;
                            if ("1" === status && "00000000" === error) {
                                this.$message.success(this.$t('common.successfulOperation'));
                                this.configurationDialog.showConfigurationDialog = false;
                            }
                        });
                    }
                });
            }
        },
        filters: {
            deductionType(deductionType){
                switch (deductionType) {
                    case 0:
                        return that.$t('common.validityRemit');// 有效期减免
                    case 1:
                        return that.$t('common.foreverRemit');// 永久性减免
                    default:
                        return '-';
                }
            }
        },
        created() {
            this.domain = this.$storage.get('user').domain
            this.showSpread = domain.showSpread();
            that = this;
            this.tableMaxHeight = document.body.clientHeight - 280;
            this.getTableData();
        }
    };
</script>

<style lang="scss" scoped>
    /deep/ .el-dialog {
        width: 500px;
        .el-form-item {
            margin-bottom: 0px;
        }
        .el-form-item__label {
            line-height: 30px;
        }
        .el-form-item__content {
            line-height: 30px;
        }

    }
</style>
